import { appWidth, divide, unitPrecision } from "@/config";

export const filterParams = (object: any) => {
  if (isEmptyType(object)) return object;
  const tmpObject: any = {};
  Object.keys(object).forEach(key => {
    if (!isEmptyType(object[key])) {
      tmpObject[key] = object[key];
    }
  });
  return tmpObject;
};

export const pxChangeRem = (px: number | string) => {
  px = parseFloat(px as string);
  const value =
    Math.round((px / (appWidth / divide)) * divide ** unitPrecision) /
    10 ** unitPrecision;
  return value + "rem";
};

export const getImg = (str: string) => {
  return new URL(`../assets/img/${str}`, import.meta.url).href;
};
export const getSvg = (str: string) => {
  return new URL(`../assets/svg/${str}.svg`, import.meta.url).href;
};
export const getIcon = (str: any) => {
  return new URL(`../assets/icons/${str}`, import.meta.url).href;
};
export const getVideo = (str: any) => {
  return new URL(`../assets/video/${str}`, import.meta.url).href;
};

export function getSearchOrHashParam(key: string): string | null {
  // 获取search参数
  const searchParams = new URLSearchParams(window.location.search);
  const searchValue = searchParams.get(key);

  if (searchValue !== null) {
    return searchValue;
  }

  // 获取hash中的search参数
  const hash = window.location.hash;
  const hashSearchMatch = hash.match(/(?<=#.*\?).*/);
  if (hashSearchMatch) {
    const hashSearchParams = new URLSearchParams(hashSearchMatch[0]);
    return hashSearchParams.get(key);
  }

  return null;
}

export function buildUrl(url: string, params: any) {
  let queryString = "";
  for (const key in params) {
    if (params.hasOwnProperty(key) && !isEmptyType(params[key])) {
      queryString +=
        encodeURIComponent(key) + "=" + encodeURIComponent(params[key]) + "&";
    }
  }
  queryString = queryString.slice(0, -1);
  return !isEmptyType(url) ? url + "?" + queryString : queryString;
}

export function debounce(fn: Function, delay: number = 300) {
  let timer: any = null;
  return function (...args: any[]) {
    if (timer) clearTimeout(timer);
    timer = setTimeout(fn.bind(null, ...args), delay);
  };
}

export function chunkArray(array: any[], size: number) {
  let result = [];
  for (let i = 0; i < array.length; i += size) {
    result.push(array.slice(i, i + size));
  }
  return result;
}

export function sortedJsonString(obj: { [x: string]: any }) {
  const sortedKeys = Object.keys(obj).sort();
  const queryString = sortedKeys.map(key => `${key}=${obj[key]}`).join("&");
  return queryString;
}
export const insertAdvert = (arr: any[], insetObj = {}, gap = 5) => {
  const result = [];
  for (let i = 0; i < arr.length; i++) {
    result.push(arr[i]);
    // 每隔5个元素插入一个0
    if ((i + 1) % gap === 0) {
      result.push(insetObj);
    }
  }
  return result;
};
